package org.ccay.validator.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

/**
 * 
 * 特殊字符验证器 [A-Za-z0-9_]  只包含大小写字符+数字 _
 * 
 * @since 2012-1-12
 */
public class AlphanumValidator extends FieldValidatorSupport {
	
	public void validate(Object object) throws ValidationException {
		String fieldName = getFieldName();
		Object value = getFieldValue(fieldName, object);
		//如果为空 那么直接返回
		if (value == null || "".equals(value.toString())){
			return;
		}
		//对前后空格不报错，插入数据库时清除前后空格
		String letter_number_regexp = "^\\s*[A-Za-z0-9_-]+\\s*$";
		Pattern pattern = Pattern.compile(letter_number_regexp);
		Matcher matcher = pattern.matcher(value.toString());
		//验证不通过 插入异常信息
		if (!matcher.matches()){
		     addFieldError(fieldName, object);
		}
	}
}
